<script setup>
import topNav from "../../components/topNav.vue";
import { onMounted, reactive, ref, getCurrentInstance, computed } from "vue";
import { onLoad, onReachBottom, onShow } from "@dcloudio/uni-app";
// import { PurchaseDet, PurchaseCancel } from "@/services/delivery";
import { orderDetail, orderVerify } from "@/services/cancellation";
import {
  PlanDetail,
  PlanStatus,
  PlanCancel,
  PlanReceive,
} from "@/services/requiregoods.js";

const id = ref("");
const detailData = ref({});
const listTabs = ref([]);

onLoad((e) => {
  id.value = e.id;
  // getPurchaseCountObj();
  getPurchaseDet();
});

const getPurchaseCountObj = async () => {
  try {
    let res = await PlanStatus();
    listTabs.value = [];
    listTabs.value.push({
      name: "全部",
      available: 0,
    });

    for (let key in res.data) {
      console.log(key, res.data[key]);

      listTabs.value.push({
        name: res.data[key],
        available: key,
      });
    }
    getPurchaseDet();
  } catch (e) {}
};
const selectStatus = (num, list) => {
  let arr = list.filter((item) => {
    return item.available == num;
  });
  return arr[0] && arr[0].name;
};

const getPurchaseDet = async (index) => {
  try {
    let res = await orderDetail({ id: id.value });
    if (res.code == 200) {
      res.data.orderProduct.forEach((element) => {
        element.total_num = element.product_num;
      });
      detailData.value = res.data;
    } else {
    }

    console.log(res);
  } catch (e) {}
};

const sandfun = () => {
  uni.navigateTo({
    url: "/pages/sends/list/index",
  });
  uni.navigateTo({
    url: "/pages/sends/list/index?id=" + id.value,
  });
};
const showLen = ref(3);

const showLenFun = () => {
  console.log(showLen.value);
  if (showLen.value > 3) {
    showLen.value = 3;
  } else {
    showLen.value = detailData.value.orderProduct.length;
  }
};

const callPhone = (phone) => {
  uni.makePhoneCall({
    phoneNumber: phone,
  });
};

const cancelFun = async () => {
  uni.showModal({
    title: "提示",
    content: "确定取消该要货计划吗？",
    success: async (res) => {
      if (res.confirm) {
        console.log("用户点击确定");
        const res = await PlanCancel({ id: id.value });
        if (res.code == 200) {
          uni.showToast({
            title: "取消成功",
            icon: "none",
          });
          uni.navigateBack();
        }
      } else if (res.cancel) {
        console.log("用户点击取消");
      }
    },
  });
};

const upFun = () => {
  uni.navigateTo({
    url: "/pages/require_goods/goods_sel/index?id=" + id.value,
  });
};

const copy = (str) => {
  uni.setClipboardData({
    data: str,
    success: function () {
      uni.showToast({
        title: "复制成功",
        icon: "none",
      });
    },
  });
};

const showP = ref(false);
const goodsList = ref([]);
const order_id = ref("");
const verifyCode = ref("");
const isTK = ref(false);
const takeFun = () => {
  detailData.value.orderProduct.forEach((element) => {
    if (element.is_refund >= 1) {
      if (element.refund_num <= 0) {
        element.product_num = 0;
        element.num = 0;
      } else {
        element.num = element.refund_num;
        element.product_num = element.refund_num;
      }
    } else {
      element.num = element.product_num;
    }
  });
  goodsList.value = detailData.value.orderProduct;
  order_id.value = detailData.value.order_id;
  verifyCode.value = detailData.value.verify_code;
  isTK.value = false;
  showP.value = true;
  // uni.showModal({
  //   title: "提示",
  //   content: "请检测货物数量是否正确，是否确定收货？",
  //   success: async (res) => {
  //     if (res.confirm) {
  //       console.log("用户点击确定");
  //       const res = await PlanReceive({ id: id.value });
  //       if (res.code == 200) {
  //         uni.showToast({
  //           title: "确认收货成功",
  //           icon: "none",
  //         });
  //         uni.navigateBack();
  //       }
  //     } else if (res.cancel) {
  //       console.log("用户点击取消");
  //     }
  //   },
  // });
};

const goRecord = async () => {
  if (isTK.value) {
    return;
  }
  isTK.value = true;

  let datas = [],
    isU = false;
  goodsList.value.forEach((item) => {
    if (item.num > 0) {
      datas.push({
        id: item.order_product_id,
        num: item.num,
      });
      isU = true;
    }
  });
  if (!isU) {
    uni.showToast({
      title: "请选择核銷商品",
      icon: "none",
    });
    return;
  }
  console.log("datas", datas);

  try {
    let res = await orderVerify({
      id: order_id.value,
      data: datas,
      verifyCode: verifyCode.value,
    });
    console.log("核销结果", res);

    if (res.code == 200) {
      uni.showToast({
        title: "核销成功",
        icon: "success",
      });
      isTK.value = false;
      showP.value = false;
      uni.navigateBack();
      // getPurchaseDet();
      // setTimeout(() => {
      //   uni.navigateTo({
      //     url: "/pages/cancellation/list/index",
      //   });
      //      isTK.value = false;
      // }, 1500);
    } else {
      uni.showToast({
        title: res.msg,
        icon: "none",
      });
      isTK.value = false;
    }
  } catch (e) {
    isTK.value = false;
    uni.showToast({
      title: e.msg,
      icon: "none",
    });
  }
};
</script>

<template>
  <topNav
    title="线上订单详情"
    @search="searchFun"
    @scan="scanFun"
    rType="save"
    :clickable="false"
  ></topNav>

  <view class="goods_state">
    <view class="goods_state-right">
      <text
        >{{
          detailData.status == -1
            ? "已退款"
            : detailData.status != -1 && detailData.verify_time
            ? "已核销"
            : detailData.status != -1 && !detailData.verify_time
            ? "待核销"
            : ""
        }}
      </text>
    </view>
    <view class="goods_state-left">
      <image
        v-if="detailData.status != -1 && !detailData.verify_time"
        src="@/static/cashier/statepage.png"
        mode="scaleToFill"
      />
      <image v-else src="@/static/cashier/yespage.png" mode="scaleToFill" />
    </view>
  </view>
  <view class="ps_k">
    <view class="ps_address"
      ><view class="left">
        <image src="@/static/home/shopme.png" mode="scaleToFill" />
        <text
          >{{ detailData.real_name }} &nbsp;{{ detailData.user_phone }}</text
        >
      </view>
      <view class="right" @click="callPhone(detailData.user_phone)"
        >打电话</view
      >
    </view>
    <view class="ps_address ps_address2"
      ><view class="left">
        <image src="@/static/home/shopin.png" mode="scaleToFill" />
        <text>{{ detailData.takes && detailData.takes.take_name }}</text>
      </view>
    </view>
    <view class="ps_address ps_address3"
      ><view class="left-to">
        <text>{{ detailData.takes && detailData.takes.address }}</text>
      </view>
    </view>
    <!-- <view class="ps_date">期望送达日期：{{ detailData.expectDate }}</view> -->
  </view>

  <view class="content">
    <view class="top">
      <view class="item_title_left">
        <text>商品信息</text>
        <!-- <image src="@/static/images/copy.png" mode="scaleToFill" /> -->
      </view>
      <!-- <up-copy :content="detailData.order_sn">
        <view class="item_title_left">
          <text>单据号：{{ detailData.order_sn }}</text>
          <image src="@/static/images/copy.png" mode="scaleToFill" />
        </view>
      </up-copy> -->
    </view>
    <view class="list">
      <view
        class="list_item"
        v-for="(item, index) in detailData.orderProduct"
        :key="index"
      >
        <view v-if="index < showLen" class="list_item_k">
          <view class="item_title_left">
            <!-- <view class="ts notice" v-if="item.isStandard == 0">非标品</view>
            <view class="ts notice-no" v-if="item.isStandard == 1">标品</view> -->
            <image
              :src="
                item.cart_info.productAttr.image ||
                'https://cloud-erp.yibaitao.cn/0d2f4178-7754-4686-9213-b174f745258b.png'
              "
              mode="scaleToFill"
            />
            <view class="info">
              <view class="info_title"
                ><text class="name">{{
                  item.cart_info.product.store_name
                }}</text>
                <view
                  ><text>x</text> {{ item.total_num
                  }}{{ item.productUnit }}</view
                ></view
              >

              <view class="info_dec"
                ><text> 商品规格: {{ item.cart_info.productAttr.sku }}</text>

                <text v-if="item.is_refund >= 1" class="refund">
                  {{
                    item.is_refund == 1
                      ? "退款中"
                      : item.is_refund == 2
                      ? "部分退款"
                      : item.is_refund == 3
                      ? "退款"
                      : ""
                  }}
                  x
                  {{
                    item.refund_num <= 0
                      ? item.total_num
                      : item.total_num - item.refund_num
                  }}</text
                >
              </view>
              <view
                class="info_price"
                :class="item.cart_info.product.price ? '' : 'no'"
                >{{
                  item.cart_info.product.price
                    ? "¥" + item.cart_info.product.price
                    : "暂无报价"
                }}
              </view>

              <!-- <view class="des-of" @click="goSHDet()">查看收货单</view> -->
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="more">
      <text
        class="more-text"
        @click="showLenFun"
        v-if="
          showLen <= 3 &&
          (detailData.orderProduct && detailData.orderProduct.length) > 3
        "
      >
        还有{{
          (detailData.orderProduct && detailData.orderProduct.length) - showLen
        }}种商品
      </text>
      <up-icon
        v-if="
          showLen <= 3 &&
          (detailData.orderProduct && detailData.orderProduct.length) > 3
        "
        class="arrow-right-double"
        name="arrow-right-double"
        size="24rpx"
        color="#999999"
      />
      <text class="more-text" @click="showLenFun" v-if="showLen > 3">
        关闭展开
      </text>
      <up-icon
        v-if="showLen > 3"
        class="arrow-right-double2"
        name="arrow-right-double"
        size="24rpx"
        color="#999999"
      />
    </view>
    <view class="pay_order">
      <text>合计</text>
      <text
        ><text>{{ detailData.total_num }}件</text>&nbsp;
        <text class="price">¥{{ detailData.total_price }}</text>
      </text>
    </view>
    <!-- <view class="pay_order">
      <text>下单总额</text>
      <text>¥{{ detailData.totalAmount }}</text>
    </view> -->
    <!-- 
    <view class="pay_num">
      实收： <text>¥{{ detailData.totalAmount }}</text>
    </view> -->
  </view>

  <!-- <view class="goods-psLis">
    <view
      class="goods-psLis-item"
      v-for="(item, index) in detailData.products"
      :key="index"
    >
      <view class="goods-psLis-item-left">
        <view class="ts notice" v-if="item.isStandard == 0">非标品</view>
        <view class="ts notice-no" v-if="item.isStandard == 1">标品</view>
        <image :src="item.image" mode="scaleToFill" />
      </view>

      <view class="goods-psLis-right">
        <view class="info">
          <text>{{ item.productName }}</text>
          <view>已接收：{{ item.receiveNum }}</view>
        </view>
        <view class="info-num"
          ><text>x</text> {{ item.orderNum }}{{ item.unit }}</view
        >
      </view>
    </view>
  </view> -->

  <view class="order_info">
    <view class="order_info_top">订单信息</view>
    <view class="order_item">
      <text>订单编号</text>
      <text
        >{{ detailData.order_sn }}
        <text class="copy" @click="copy(detailData.order_sn)">复制</text></text
      >
    </view>
    <view class="order_item">
      <text>支付时间</text>
      <text>{{ detailData.pay_time }}</text>
    </view>
    <view class="order_item">
      <text>支付金额</text>
      <text>{{ detailData.pay_price }}元</text>
    </view>
    <!-- <view class="order_item">
      <text>创建人</text>
      <text>{{ detailData.createBy }}</text>
    </view> -->
    <!-- <view class="order_item">
      <text>期望到货日期</text>
      <text>{{ detailData.expectArriveDate }}</text>
    </view> -->
    <!-- <view class="order_item">
      <text>结算方式</text>
      <text>售出结算</text>
    </view> -->
  </view>
  <view style="width: 100%; height: 150rpx"></view>

  <view
    class="goods_bt"
    v-if="detailData.status != -1 && !detailData.verify_time"
  >
    <view class="goods_bt_to">
      <view
        v-permission="['shop:mulin:order:verify']"
        class="bt_fh bt_qr"
        @click.stop="takeFun"
        v-if="detailData.status != -1 && !detailData.verify_time"
        >核销订单</view
      >
    </view>
  </view>

  <up-popup
    :show="showP"
    :closeOnClickOverlay="true"
    mode="bottom"
    @close="showP = false"
    round="15rpx"
    :closeable="true"
  >
    <view class="sel_p">
      <view class="sel_p-title">订单核销</view>

      <view>
        <scroll-view scroll-y="true" class="scroll-Y">
          <view
            class="scroll-Y-item"
            v-for="(item, index) in goodsList"
            :key="index"
          >
            <view class="content-item">
              <view class="content-item-left">
                <!-- <text class="goods-item-cz"
              >{{ item.dhCode ? "称重" : "计件" }} </text
            > -->
                <image
                  :src="item.cart_info.productAttr.image"
                  mode="scaleToFill"
              /></view>
              <view class="content-item-right">
                <view class="content-item-right-title">
                  <text>{{ item.cart_info.product.store_name }}</text>
                </view>

                <view class="content-item-right-num">
                  <view class="content-item-right-num-gg"
                    ><text>{{ item.cart_info.productAttr.sku }}</text>
                  </view>
                  <view class="content-item-right-num-left"
                    ><text>{{ item.categoryName }}</text>
                  </view>
                  <view class="content-item-right-num-right">
                    <up-number-box
                      v-model="item.num"
                      min="0"
                      :max="item.product_num"
                    ></up-number-box>
                  </view>
                </view>

                <view class="content-item-right-price">
                  <view
                    ><text>¥</text
                    >{{
                      item.cart_info.product.price
                        ? item.cart_info.product.price
                        : "0"
                    }}
                    &nbsp;
                  </view>
                  <view class="refund" v-if="item.is_refund >= 1"
                    >{{
                      item.is_refund == 1
                        ? "退款中"
                        : item.is_refund == 2
                        ? "部分退款"
                        : item.is_refund == 3
                        ? "退款"
                        : ""
                    }}x{{ item.total_num - item.refund_num }}</view
                  >
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="goods_bt_to">
        <van-button class="val-button" type="primary" @click="goRecord"
          >确认核销</van-button
        >
      </view>
    </view>
  </up-popup>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
